package com.lilicould.service;

import com.google.gson.Gson;
import com.lilicould.dao.ClassDao;
import com.lilicould.entity.Classes;
import com.lilicould.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

public class ClassService {
    public String getAllClass() {
        try(SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            ClassDao classDao = sqlSession.getMapper(ClassDao.class);
            return new Gson().toJson(classDao.getAllClass());
        } catch (Exception e) {
            return null;
        }
    }

    public String addClass(Classes clazz) {
        try(SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            ClassDao classDao = sqlSession.getMapper(ClassDao.class);
            int result = classDao.addClass(clazz);
            if (result > 0) {
                // 添加成功,提交事务,返回空值
                sqlSession.commit();
                return null;
            }else {
                // 添加失败,返回错误信息
                return "添加失败";
            }
        }catch (Exception e) {
            // 添加失败，返回错误信息
            return e.getMessage();
        }
    }

    public String deleteClass(String classCode, String majorCode, String collegeCode) {
        try(SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            ClassDao classDao = sqlSession.getMapper(ClassDao.class);
            int result = classDao.deleteClass(classCode, majorCode, collegeCode);
            if (result > 0) {
                // 删除成功,提交事务,返回空值
                sqlSession.commit();
                return null;
            } else {
                // 删除失败,返回错误信息
                return "删除失败";
            }
        }catch (Exception e) {
            return e.getMessage();
        }
    }
}
